// 登录模块控制器
class LoginController {
    constructor() {
        this.form = document.getElementById('loginForm');
        this.usernameInput = document.getElementById('username');
        this.passwordInput = document.getElementById('password');
        this.rememberMe = document.getElementById('rememberMe');
        this.loginBtn = document.getElementById('loginBtn');
        this.message = document.getElementById('loginMessage');
        
        this.init();
    }
    
    init() {
        this.bindEvents();
        this.loadRememberedUser();
    }
    
    bindEvents() {
        // 表单提交事件
        this.form.addEventListener('submit', (e) => this.handleSubmit(e));
        
        // 实时验证
        this.usernameInput.addEventListener('input', () => this.validateUsername());
        this.passwordInput.addEventListener('input', () => this.validatePassword());
        
        // 记住我状态变化
        this.rememberMe.addEventListener('change', () => this.handleRememberMe());
    }
    
    handleSubmit(e) {
        e.preventDefault();
        
        // 验证所有字段
        const isUsernameValid = this.validateUsername();
        const isPasswordValid = this.validatePassword();
        
        if (isUsernameValid && isPasswordValid) {
            this.performLogin();
        } else {
            this.showMessage('请正确填写所有字段', 'error');
        }
    }
    
    validateUsername() {
        const username = this.usernameInput.value.trim();
        const errorElement = document.getElementById('usernameError');
        
        if (!username) {
            this.showError(errorElement, '用户名不能为空');
            return false;
        }
        
        if (username.length < 3) {
            this.showError(errorElement, '用户名至少3个字符');
            return false;
        }
        
        this.hideError(errorElement);
        return true;
    }
    
    validatePassword() {
        const password = this.passwordInput.value;
        const errorElement = document.getElementById('passwordError');
        
        if (!password) {
            this.showError(errorElement, '密码不能为空');
            return false;
        }
        
        if (password.length < 6) {
            this.showError(errorElement, '密码至少6个字符');
            return false;
        }
        
        this.hideError(errorElement);
        return true;
    }
    
    showError(errorElement, message) {
        errorElement.textContent = message;
        errorElement.classList.add('show');
        errorElement.previousElementSibling.classList.add('error');
    }
    
    hideError(errorElement) {
        errorElement.textContent = '';
        errorElement.classList.remove('show');
        errorElement.previousElementSibling.classList.remove('error');
    }
    
    async performLogin() {
        // 禁用登录按钮
        this.loginBtn.disabled = true;
        this.loginBtn.textContent = '登录中...';
        
        try {
            // 模拟API调用
            await this.simulateApiCall();
            
            // 保存记住我状态
            if (this.rememberMe.checked) {
                this.saveUserCredentials();
            } else {
                this.clearUserCredentials();
            }
            
            this.showMessage('登录成功！正在跳转...', 'success');
            
            // 模拟跳转
            setTimeout(() => {
                this.showMessage('跳转到首页...', 'success');
                // 实际项目中这里应该是 window.location.href = '/dashboard';
            }, 1500);
            
        } catch (error) {
            this.showMessage('登录失败：用户名或密码错误', 'error');
        } finally {
            // 恢复登录按钮
            this.loginBtn.disabled = false;
            this.loginBtn.textContent = '登录';
        }
    }
    
    simulateApiCall() {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                const username = this.usernameInput.value.trim();
                const password = this.passwordInput.value;
                
                // 模拟验证逻辑（实际项目中应该调用真实API）
                if (username === 'admin' && password === '123456') {
                    resolve({ success: true, token: 'mock-jwt-token' });
                } else {
                    reject(new Error('认证失败'));
                }
            }, 1000);
        });
    }
    
    handleRememberMe() {
        if (!this.rememberMe.checked) {
            this.clearUserCredentials();
        }
    }
    
    saveUserCredentials() {
        const credentials = {
            username: this.usernameInput.value.trim(),
            remember: true
        };
        localStorage.setItem('userCredentials', JSON.stringify(credentials));
    }
    
    clearUserCredentials() {
        localStorage.removeItem('userCredentials');
    }
    
    loadRememberedUser() {
        const saved = localStorage.getItem('userCredentials');
        if (saved) {
            try {
                const credentials = JSON.parse(saved);
                if (credentials.remember && credentials.username) {
                    this.usernameInput.value = credentials.username;
                    this.rememberMe.checked = true;
                }
            } catch (error) {
                console.warn('加载保存的用户信息失败');
            }
        }
    }
    
    showMessage(text, type) {
        this.message.textContent = text;
        this.message.className = `message ${type} show`;
        
        // 3秒后自动隐藏消息
        setTimeout(() => {
            this.message.classList.remove('show');
        }, 3000);
    }
}

// 页面加载完成后初始化登录控制器
document.addEventListener('DOMContentLoaded', () => {
    new LoginController();
});

// 导出控制器类（如果需要在其他模块中使用）
if (typeof module !== 'undefined' && module.exports) {
    module.exports = LoginController;
}